package com.api.shuigui.web;

import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.Util;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 附件下载
 *
 * @author 泛微-何汶俊
 * @date 2023-01-10 22:11
 */
@WebServlet("/doc/sg/download")
public class FileDownDoc extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        int fileid = Util.getIntValue(req.getParameter("fileid"));
        InputStream imagefile = null;
        try {
            ImageFileManager ifm = new ImageFileManager();
            ifm.getImageFileInfoById(fileid);
            imagefile = ifm.getInputStream();
            String filename = ifm.getImageFileName();
            String contenttype = "";
            if(filename.toLowerCase().endsWith(".gif")) {
                contenttype = "image/gif";
                res.addHeader("Cache-Control", "private, max-age=8640000");
            }else if(filename.toLowerCase().endsWith(".png")) {
                contenttype = "image/png";
                res.addHeader("Cache-Control", "private, max-age=8640000");
            }else if(filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg")) {
                contenttype = "image/jpg";
                res.addHeader("Cache-Control", "private, max-age=8640000");
            }else if(filename.toLowerCase().endsWith(".bmp")) {
                contenttype = "image/bmp";
                res.addHeader("Cache-Control", "private, max-age=8640000");
            }
            ServletOutputStream out = res.getOutputStream();
            res.setContentType(contenttype);
            res.setHeader("content-disposition", "attachment; filename=\"" +  new String(filename.replaceAll("<", "").replaceAll(">", "").replaceAll("&lt;", "").replaceAll("&gt;", "").getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)+"\"");
            int byteread;
            byte data[] = new byte[1024];
            while ((byteread = imagefile.read(data)) != -1) {
                out.write(data, 0, byteread);
                out.flush();
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            new BaseBean().writeLog(e);
        } finally {
            if(imagefile != null){
                imagefile.close();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        super.doPost(req, res);
    }
}
